from fastapi import APIRouter, Depends, Request
from sqlalchemy.ext.asyncio import AsyncSession

from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_kylin.entity.vo.future_settlement_vo import (
    BatchFutureSettlementDownloadModel,
    DeleteFutureSettlementModel,
    FutureSettlementDownloadModel,
    FutureSettlementModel,
    FutureSettlementPageQueryModel,
    ImportSettlementToDailyModel,
)
from module_kylin.service.future_settlement_service import FutureSettlementService
from utils.log_util import logger
from utils.response_util import ResponseUtil

futureSettlementController = APIRouter(
    prefix='/kylin/futureSettlement', dependencies=[Depends(LoginService.get_current_user)]
)


@futureSettlementController.get('/list', dependencies=[Depends(CheckUserInterfaceAuth('kylin:futureSettlement:list'))])
async def get_future_settlement_list(
    request: Request,
    page_query_model: FutureSettlementPageQueryModel = Depends(FutureSettlementPageQueryModel.as_query),
    query_db: AsyncSession = Depends(get_db),
):
    """
    获取期货结算单列表
    """
    settlement_list_result = await FutureSettlementService.get_settlement_list(query_db, page_query_model, is_page=True)
    logger.info('获取期货结算单列表成功')
    return ResponseUtil.success(data=settlement_list_result)


@futureSettlementController.get(
    '/{id}',
    response_model=FutureSettlementModel,
    dependencies=[Depends(CheckUserInterfaceAuth('kylin:futureSettlement:query'))],
)
async def query_detail_future_settlement(
    request: Request,
    id: int,
    query_db: AsyncSession = Depends(get_db),
):
    """
    获取期货结算单详情
    """
    settlement_detail_result = await FutureSettlementService.get_settlement_detail(query_db, id)
    logger.info(f'获取结算单id为{id}的信息成功')
    return ResponseUtil.success(data=settlement_detail_result)


@futureSettlementController.post(
    '/', response_model=CrudResponseModel, dependencies=[Depends(CheckUserInterfaceAuth('kylin:futureSettlement:add'))]
)
@Log(title='期货结算单管理', business_type=BusinessType.INSERT)
async def add_future_settlement(
    request: Request,
    settlement: FutureSettlementModel,
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
    query_db: AsyncSession = Depends(get_db),
):
    """
    新增期货结算单
    """
    try:
        result = await FutureSettlementService.add_settlement(query_db, settlement)
        logger.info('添加期货结算单成功')
        return ResponseUtil.success(msg=result)
    except Exception as e:
        logger.error(f'添加期货结算单失败: {str(e)}')
        return ResponseUtil.error(msg=f'添加失败: {str(e)}')


@futureSettlementController.put(
    '/{id}',
    response_model=CrudResponseModel,
    dependencies=[Depends(CheckUserInterfaceAuth('kylin:futureSettlement:edit'))],
)
@Log(title='期货结算单管理', business_type=BusinessType.UPDATE)
async def update_future_settlement(
    request: Request,
    id: int,
    settlement: FutureSettlementModel,
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
    query_db: AsyncSession = Depends(get_db),
):
    """
    更新期货结算单
    """
    result = await FutureSettlementService.update_settlement(query_db, id, settlement)
    logger.info('更新期货结算单成功')
    return ResponseUtil.success(msg=result)


@futureSettlementController.delete(
    '/',
    response_model=CrudResponseModel,
    dependencies=[Depends(CheckUserInterfaceAuth('kylin:futureSettlement:remove'))],
)
@Log(title='期货结算单管理', business_type=BusinessType.DELETE)
async def delete_future_settlement(
    request: Request,
    delete_model: DeleteFutureSettlementModel,
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
    query_db: AsyncSession = Depends(get_db),
):
    """
    删除期货结算单
    """
    result = await FutureSettlementService.delete_settlement(query_db, delete_model)
    logger.info('删除期货结算单成功')
    return ResponseUtil.success(msg=result)


@futureSettlementController.post(
    '/download',
    response_model=CrudResponseModel,
    dependencies=[Depends(CheckUserInterfaceAuth('kylin:futureSettlement:download'))],
)
@Log(title='期货结算单管理', business_type=BusinessType.EXPORT)
async def download_future_settlement(
    request: Request, download_model: FutureSettlementDownloadModel, db: AsyncSession = Depends(get_db)
):
    """
    下载指定日期的期货结算单
    通过用户名、密码和日期从中国期货市场监控中心登录并下载结算单
    """
    try:
        result = await FutureSettlementService.download_settlement(db, download_model)
        logger.info(f'结算单下载成功: {result}')
        # 现在download_settlement返回的是JSON对象，直接作为data返回
        return ResponseUtil.success(msg=result["message"], data=result)
    except Exception as e:
        logger.error(f'结算单下载失败: {str(e)}')
        # 使用ResponseUtil统一处理错误响应
        return ResponseUtil.error(msg=str(e))


@futureSettlementController.post(
    '/batchDownload',
    response_model=CrudResponseModel,
    dependencies=[Depends(CheckUserInterfaceAuth('kylin:futureSettlement:download'))],
)
@Log(title='期货结算单管理', business_type=BusinessType.EXPORT)
async def batch_download_future_settlement(
    request: Request, download_model: BatchFutureSettlementDownloadModel, db: AsyncSession = Depends(get_db)
):
    """
    批量下载期货结算单
    支持多个账户、日期范围、结算单类型和盈亏计算方式的批量下载
    """
    try:
        result = await FutureSettlementService.batch_download_settlement(db, download_model)
        logger.info(f'批量结算单下载完成: {result}')
        return ResponseUtil.success(msg=f'批量下载完成，总任务数: {result["total_tasks"]}, 成功: {result["success_count"]}, 跳过: {result["skip_count"]}, 失败: {result["fail_count"]}', data=result)
    except Exception as e:
        logger.error(f'批量结算单下载失败: {str(e)}')
        return ResponseUtil.error(msg=str(e))


@futureSettlementController.post(
    '/importToDaily',
    response_model=CrudResponseModel,
    dependencies=[Depends(CheckUserInterfaceAuth('kylin:futureSettlement:import'))],
)
@Log(title='期货结算单管理', business_type=BusinessType.IMPORT)
async def import_settlement_to_daily(
    request: Request,
    import_model: ImportSettlementToDailyModel,
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
    query_db: AsyncSession = Depends(get_db),
):
    """
    导入期货结算单到资金日报
    从assets/settlements目录读取结算单文件，提取资金信息并导入到期货账户资金日报
    """
    try:
        result = await FutureSettlementService.import_settlement_to_daily(query_db, import_model)
        logger.info(f'导入结算单到资金日报成功: {import_model.account_code} {import_model.settlement_date}')
        return ResponseUtil.success(msg=result)
    except Exception as e:
        logger.error(f'导入结算单到资金日报失败: {str(e)}')
        return ResponseUtil.error(msg=str(e))
